// 地址解析函数（核心逻辑）
function parseAddress(fullAddress) {
  // 步骤1：分割姓名、地址和电话
  const [addressPart, name, phone] = fullAddress.split(/\s+/).filter(Boolean);

  // 步骤2：使用正则解析省市区街道
  const pattern = /^(.+?[省市])(.+?[市区州])(.+?[市区县])(.+)$/;
  const match = addressPart.match(pattern);

  if (!match) throw new Error('地址格式解析失败');

  return {
    province: match[1].replace(/[省市]$/, ''),
    city: match[2].replace(/[市区州]$/, ''),
    district: match[3].replace(/[市区县]$/, ''),
    street: match[4],
    name,
    phone,
    detail: match[4] // 街道即为详细地址
  };
  return colors[type] || 'black';
}

function printAddress2(fullAddress) {
  // 步骤1：分割姓名、地址和电话
  let [addressPart, name, phone1] = fullAddress.split(/\s+/).filter(Boolean);
  let phone = '';
  // debugLog('info', '原始地址1:', fullAddress);
  if (phone1.includes('-')) {
    // debugLog('info', '虚拟号码:', phone1);
    phone = phone1.split('-')[0];
    // debugLog('info', '虚拟号码:', phone1);
    const phoneId = phone1.split('-')[1];

    // name = concat(name, '-', phoneId);
    name = `${name}${phoneId}`; // 直接拼接字符串
    // addressPart = concat(addressPart, '【', phone1, '】');
    addressPart = `${addressPart},${phone1}`;
  } else {
    phone = phone1;
  }
  // debugLog('info', phone);
  // debugLog('info', '原始地址2:', addressPart);
  // 步骤2：解析完整的行政区域路径（省→市→区→街道）
  const region = extractFullRegionPath(addressPart);

  return {
    region,      // 格式：广东省深圳市罗湖区翠竹街道
    detail: addressPart.replace(region, "").trim(), // 剩余部分为详细地址
    name: name?.trim() || "",
    phone: phone?.trim() || ""
  };
}

function isNumberStr(str) {
  // 先将字符串转换为数字，然后检查是否为非NaN值
  return !isNaN(Number(str));
}

function printAddress3(fullAddress) {
  // 步骤1：分割字符串为部分，但不假设顺序
  const parts = fullAddress.split(/\s+/).filter(Boolean);

  debugLog('info', '拆分数组:', parts);
  // 步骤2：根据内容特征识别各部分
  let addressPart = '';
  let name = '';
  let phone = '';
  let phone1 = '';


  // 地址正则表达式：包含省市区等关键字
  const addressRegex = /[省市县区街道镇乡村]/;

  // 遍历所有部分，根据特征分类
  for (let part of parts) {
    // 检查是否为普通号码
    if (part.length == 11 && part.slice(0, 1) == '1' && isNumberStr(part)) {
      phone1 = part;
    }
    // 检查是否为虚拟号码
    else if (part.includes('-') && isNumberStr(part.replace('-', ''))) {
      phone1 = part;
    }
    // 检查是否包含地址关键字
    else if (addressRegex.test(part)) {
      addressPart += (addressPart ? ' ' : '') + part;
    }
    // 剩余部分默认为姓名
    else {
      name += (name ? ' ' : '') + part;
    }
  }

  const ad = {
    name: name,
    phone: phone1,
    address: addressPart,
  };
  debugLog('info', '识别信息:', ad);
  // debugLog('info', '原始地址1:', fullAddress);
  if (phone1.includes('-')) {
    // debugLog('info', '虚拟号码:', phone1);
    phone = phone1.split('-')[0];
    // debugLog('info', '虚拟号码:', phone1);
    const phoneId = phone1.split('-')[1];

    // name = concat(name, '-', phoneId);
    name = `${name}${phoneId}`; // 直接拼接字符串
    // addressPart = concat(addressPart, '【', phone1, '】');
    addressPart = `${addressPart},${phone1}`;
  } else {
    phone = phone1;
  }
  // debugLog('info', phone);
  // debugLog('info', '原始地址2:', addressPart);
  // 步骤2：解析完整的行政区域路径（省→市→区→街道）
  const region = extractFullRegionPath(addressPart);

  return {
    region,      // 格式：广东省深圳市罗湖区翠竹街道
    detail: addressPart.replace(region, "").trim(), // 剩余部分为详细地址
    name: name?.trim() || "",
    phone: phone?.trim() || ""
  };
}
function extractFullRegionPath(address) {
  // 正则匹配四级结构（省/市/区/街道）
  const pattern = /^(?<province>.+?(?:省|自治区|市))(?<city>.+?(?:市|自治州))(?<district>.+?(?:区|县|市))(?<street>.+?(?:街道|镇|乡))/;
  const match = address.match(pattern);

  if (match) {
    const { province, city, district, street } = match.groups;
    return `${province}${city}${district}${street}`;
  }

  // 兼容直辖市（三级结构：市→区→街道）
  const municipalityPattern = /^(?<province>北京市|天津市|上海市|重庆市)(?<district>.+?(?:区|县))(?<street>.+?(?:街道|镇|乡))/;
  const municipalityMatch = address.match(municipalityPattern);

  if (municipalityMatch) {
    const { province, district, street } = municipalityMatch.groups;
    return `${province}${province}${district}${street}`; // 直辖市重复省级名称
  }

  // 保底逻辑：返回原始地址（避免因解析失败丢失数据）
  return address;
}

// 调试日志函数
function debugLog(type, message, data = null) {
  // 发送日志到background.js
  chrome.runtime.sendMessage({
    action: 'contentDebugLog',
    logType: type,
    message: message,
    data: data
  });

  // 同时在控制台输出带样式的日志
  const color = getColorForType(type);
  console.log(`%c[Content] ${message}`, `color: ${color}`, data);
}

// 主填充函数
async function fillAddress(addressInfo) {
  try {
    // 步骤1：点击新增地址按钮
    const addBtn = document.querySelector('a.ftx-05.J_consignee_global');
    if (!addBtn) throw new Error('未找到新增地址按钮');
    addBtn.click();
    debugLog('info', '已点击新增地址按钮');

    // 等待iframe加载
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 步骤2：获取iframe文档对象
    const iframe = document.querySelector('iframe');
    if (!iframe) throw new Error('未找到地址iframe');
    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // 步骤3：填写基础信息
    fillBasicInfo(iframeDoc, addressInfo);

    // 步骤4：处理省市区选择
    const selectAdd = await selectRegion(iframeDoc, addressInfo);

    return { success: true, selectAdd: selectAdd };
  } catch (error) {
    debugLog('error', '执行失败', error.message);
    return { success: false, error: error.message };
  }
}

// 填写基础信息
function fillBasicInfo(iframeDoc, { name, phone, detail }) {
  const nameInput = iframeDoc.querySelector('input[id="consignee_name"]');
  const phoneInput = iframeDoc.querySelector('input[id="consignee_mobile"]');
  const addressInput = iframeDoc.querySelector('input[id="consignee_address"]');

  if (nameInput) nameInput.value = name;
  if (phoneInput) phoneInput.value = phone;
  if (addressInput) addressInput.value = detail;
}

// 选择省市区（核心交互逻辑）
async function selectRegion(iframeDoc, { region }) {
  // 触发区域选择框
  const areaText = iframeDoc.querySelector('div.ui-area-text');
  if (!areaText) throw new Error('未找到区域选择框');

  // 模拟鼠标悬停
  const mouseOverEvent = new MouseEvent('mouseover', {
    bubbles: true,
    cancelable: true,
    view: window
  });
  areaText.dispatchEvent(mouseOverEvent);
  debugLog('info', '已触发区域选择框');

  // 等待下拉框加载
  await new Promise(resolve => setTimeout(resolve, 500));



  let lastIndex = -1;
  let selectAdd = '';

  // 步骤1：检测是否包含直辖市名称（字符串包含检测）
  const isMunicipality =
    region.includes('北京') ||
    region.includes('天津') ||
    region.includes('上海') ||
    region.includes('重庆');


  for (let i = 0; i < 5; i++) {
    // debugLog('info', '当前层级', i);
    // 获取区域选择层
    // 正确写法：使用连续类选择器（无空格）
    const areaLayers = iframeDoc.querySelectorAll('div.ui-switchable-panel.ui-switchable-panel-selected');
    // debugLog('info', '已找到区域选择层', areaLayers);

    if (areaLayers.length === 0) {
      debugLog('info', '没有找到可选择部分');
      break;
    }

    const areaLayer = areaLayers[0];
    // debugLog('info', '已找到列表层', areaLayer);
    const dataIndex = areaLayer.getAttribute('data-index');
    const dataIndexNum = parseInt(dataIndex, 10); // 转换为整数
    // debugLog('info', '层次', dataIndex);
    if (dataIndexNum > lastIndex) {
      lastIndex = dataIndexNum;
    } else {
      debugLog('info', '层级未改变', dataIndexNum);
      break;
    }

    const options = areaLayer.querySelectorAll(`[data-id]`);
    // debugLog('info', "找到列表", options);
    // 查找匹配项

    let found = false;

    for (const option of options) {
      // debugLog('info', '当前项', option.textContent);
      if (region.includes(option.textContent)) {
        option.click();
        selectAdd += option.textContent;
        debugLog('info', `已选择: ${option.textContent}`);
        found = true;
        break;
      }
    }

    if (!found) {
      debugLog('warn', `未找到匹配项: 第${lastIndex + 1}级别`);
      throw new Error(`未找到匹配项: 第${lastIndex + 1}级别`);
    }

    // 等待下一级加载
    await new Promise(resolve => setTimeout(resolve, 500));
  }

  if (isMunicipality) {
    lastIndex += 1;
  }

  if (lastIndex !== 3) {
    throw new Error(`地址层级错误,层级:${lastIndex + 1},选中信息${selectAdd}`);
  } else {
    debugLog('info', `地址识别成功${selectAdd}`);
  }

  debugLog('info', "返回选中值", selectAdd);
  return selectAdd;
}

// 消息监听
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  debugLog('info', 'content监听消息', request);
  if (request.action === "executeFill") {
    try {
      const addressInfo = printAddress3(request.address);
      debugLog('info', '地址解析结果', addressInfo);

      fillAddress(addressInfo).then(result => {
        debugLog('info', '填充结果', result);
        sendResponse(result);
      });

      return true; // 保持异步通道
    } catch (error) {
      sendResponse({ success: false, error: error.message });
    }
  }
});

// 根据日志类型返回不同的颜色
function getColorForType(type) {
  const colors = {
    info: 'blue',
    success: 'green',
    warning: 'orange',
    error: 'red',
    detail: 'purple'
  };
  return colors[type] || 'black';
}
